package com.sugon.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.sugon.dao.SysDeptDao;
import com.sugon.dao.SysProcessInfoDao;
import com.sugon.dao.SysUserRoleDao;
import com.sugon.entity.SysDeptEntity;
import com.sugon.entity.SysProcessInfoEntity;
import com.sugon.entity.SysUserEntity;
import com.sugon.modules.sparepart.model.vo.SpareNeedsPlanApproveProcessVO;
import com.sugon.modules.sys.consts.ProcessApproveStatus;
import com.sugon.modules.sys.consts.ProcessProgressStatus;
import com.sugon.service.SysMsgService;
import com.sugon.service.SysProcessInfoService;
import com.sugon.service.SysUserRoleService;
import com.sugon.utils.ProcessInfoEnum;
import com.sugon.utils.ShiroUtils;
import com.sugon.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 流程信息Service实现类
 *
 * @author sugon
 * @date 2019-08-03 21:20:31
 */
@Service("sysProcessInfoService")
public class SysProcessInfoServiceImpl implements SysProcessInfoService {

    @Autowired
    private SysProcessInfoDao sysProcessInfoDao;
    @Autowired
    private SysUserRoleDao sysUserRoleDao;
    @Autowired
    private SysUserRoleService userRoleService;
    @Autowired
    private SysDeptDao sysDeptDao;
    @Autowired
    private SysMsgService sysMsgService;

    /**
     * @param processInfoEnum 流程类别
     * @param dataId          业务记录ID
     * @return
     */
    @Override
    public int delete(ProcessInfoEnum processInfoEnum, String dataId) {
        return sysProcessInfoDao.deleteProcessData(processInfoEnum.name(), dataId);
    }

    /**
     * @param bussinessId
     * @return
     */
    @Override
    public List<SpareNeedsPlanApproveProcessVO> getApproveList(String bussinessId) {
        List<SpareNeedsPlanApproveProcessVO> approveProcessList = sysProcessInfoDao.getApproveList(bussinessId);
        if (approveProcessList == null) {
            approveProcessList = new ArrayList<>();
        }
        return approveProcessList;
    }

    /**
     * @param id 主键
     * @return
     */
    @Override
    public SysProcessInfoEntity queryObject(String id) {
        return sysProcessInfoDao.queryObject(id);
    }

    /**
     * @param map 参数
     * @return
     */
    @Override
    public List<SysProcessInfoEntity> queryList(Map<String, Object> map) {
        return sysProcessInfoDao.queryList(map);
    }

    /**
     * @param map 参数
     * @return
     */
    @Override
    public int queryTotal(Map<String, Object> map) {
        return sysProcessInfoDao.queryTotal(map);
    }

    /**
     * @param sysProcessInfo 实体
     * @return
     */
    @Override
    public int save(SysProcessInfoEntity sysProcessInfo) {
        sysProcessInfo.setId(RandomUtil.randomString(32));
        sysProcessInfo.setCreateTime(DateUtil.date());
        return sysProcessInfoDao.save(sysProcessInfo);
    }

    /**
     * @param sysProcessInfo 实体
     * @return
     */
    @Override
    public int update(SysProcessInfoEntity sysProcessInfo) {
        return sysProcessInfoDao.update(sysProcessInfo);
    }

    /**
     * @param id
     * @return
     */
    @Override
    public int delete(String id) {
        return sysProcessInfoDao.delete(id);
    }

    /**
     * @param ids
     * @return
     */
    @Override
    public int deleteBatch(String[] ids) {
        return sysProcessInfoDao.deleteBatch(ids);
    }

    /**
     * @param processType 流程类别
     * @param dataId      关联数据项ID
     * @param remark      备注
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void startProcess(ProcessInfoEnum processType, String dataId, String remark) {
        saveProcessInfo(null, dataId, processType, ProcessApproveStatus.PASSED_WITH_APPROVE, null, remark, ProcessProgressStatus.ING);
        // 生成审批消息
        sysMsgService.generateSparePartApproveItemMsg(dataId, 0);
    }

    /**
     * @param processId
     * @param approvalType
     * @param status
     * @param newApproverId
     * @return
     */
    @Override
    public int saveProcessInfo(String processId, ProcessInfoEnum approvalType, Integer status, String newApproverId) {
        return saveProcessInfo(processId, null, approvalType, status, newApproverId, null, 0) != null ? 1 : 0;
    }

    /**
     * @param processId
     * @param approvalType
     * @param status
     * @param newApproverId
     * @param remark
     * @return
     */
    @Override
    public int saveProcessInfo(String processId, ProcessInfoEnum approvalType, Integer status, String newApproverId, String remark) {
        return saveProcessInfo(processId, null, approvalType, status, newApproverId, remark, 0) != null ? 1 : 0;
    }

    /**
     * 保存流程信息
     *
     * @param processId
     * @param dataId
     * @param approvalType
     * @param status
     * @param newApproverId
     * @param remark
     * @param isEnd
     * @return
     */
    @Override
    public SysProcessInfoEntity saveProcessInfo(String processId, String dataId, ProcessInfoEnum approvalType, Integer status, String newApproverId, String remark, Integer isEnd) {
        // 设置当前审批信息
        SysProcessInfoEntity processInfoEntity = new SysProcessInfoEntity();
        processInfoEntity.setApprovalType(approvalType.name());
        processInfoEntity.setProcessId(processId);
        processInfoEntity.setDataId(dataId);

        processInfoEntity.setOldApprovalStatus(status);
        processInfoEntity.setRemark(remark);
        processInfoEntity.setIsEnd(isEnd);
        // 获取当前登录用户，APP端登录不能识别这个
        SysUserEntity sysUserEntity = ShiroUtils.getUserEntity();
        if (sysUserEntity != null) {
            processInfoEntity.setOldApprover(sysUserEntity.getUserName());
            processInfoEntity.setOldApproverId(sysUserEntity.getUserId());
            // 设置当前审批部门
            String deptNames = null;
            String deptId = sysUserEntity.getDeptId();
            if (deptId != null) {
                SysDeptEntity deptEntity = sysDeptDao.queryObject(deptId);
                if (deptEntity != null) {
                    deptNames = getDeptNames(deptEntity.getName(), deptEntity.getParentId());
                }
            }
            processInfoEntity.setDeptName(deptNames);
            // 设置当前审批用户角色
            List<String> roleNameList = userRoleService.queryRoleNamesByProcessItem(approvalType, sysUserEntity.getUserId());
            if (CollectionUtil.isNotEmpty(roleNameList)) {
                processInfoEntity.setRoleName(roleNameList.get(0));
            }
        }

        // 设置下级审批信息
        processInfoEntity.setNewApprover(null);
        processInfoEntity.setNewApproverId(newApproverId);
        save(processInfoEntity);
        return processInfoEntity;
    }

    /**
     *
     * @param processId
     * @param approvalType
     * @param status
     * @param newApproverId
     * @param remark
     * @param loginUser
     * @return
     */
    @Override
    public int saveProcessInfoApi(String processId, ProcessInfoEnum approvalType, Integer status, String newApproverId, String remark, SysUserEntity loginUser) {
        String userId = loginUser.getUserId();
        String deptId = loginUser.getDeptId();
        String roleNames = "";
        List<String> roleNameList = sysUserRoleDao.queryRoleNameList(userId);
        for (String str : roleNameList) {
            roleNames += str + "-";
        }
        if (roleNames.length() > 0) {
            roleNames = roleNames.substring(0, roleNames.length() - 1);
        }

        SysDeptEntity deptEntity = sysDeptDao.queryObject(deptId);
        String deptNames = getDeptNames(deptEntity.getName(), deptEntity.getParentId());

        SysProcessInfoEntity processInfoEntity = new SysProcessInfoEntity();
        processInfoEntity.setId(RandomUtil.randomString(32));
        processInfoEntity.setProcessId(processId);
        processInfoEntity.setId(RandomUtil.randomString(32));
        processInfoEntity.setApprovalType(approvalType.name());
        processInfoEntity.setCreateTime(new Date());
        processInfoEntity.setOldApproverId(userId);
        processInfoEntity.setDeptName(deptNames);
        processInfoEntity.setRoleName(roleNames);

        processInfoEntity.setOldApprovalStatus(status);
        processInfoEntity.setNewApproverId(newApproverId);
        processInfoEntity.setRemark(remark);
        return sysProcessInfoDao.save(processInfoEntity);
    }

    /**
     *
     * @param processId
     * @param approvalType
     * @param status
     * @param newApproverId
     * @param remark
     * @param userId
     * @param deptId
     * @return
     */
    @Override
    public int saveProcessInfoApi2(String processId, ProcessInfoEnum approvalType, Integer status, String newApproverId, String remark, String userId, String deptId) {
        String roleNames = "";
        List<String> roleNameList = sysUserRoleDao.queryRoleNameList(userId);
        for (String str : roleNameList) {
            roleNames += str + "-";
        }
        roleNames = roleNames.substring(0, roleNames.length() - 1);

        SysDeptEntity deptEntity = sysDeptDao.queryObject(deptId);
        String deptNames = getDeptNames(deptEntity.getName(), deptEntity.getParentId());

        SysProcessInfoEntity processInfoEntity = new SysProcessInfoEntity();
        processInfoEntity.setId(RandomUtil.randomString(32));
        processInfoEntity.setProcessId(processId);
        processInfoEntity.setId(RandomUtil.randomString(32));
        processInfoEntity.setApprovalType(approvalType.name());
        processInfoEntity.setCreateTime(new Date());
        processInfoEntity.setOldApproverId(userId);
        processInfoEntity.setDeptName(deptNames);
        processInfoEntity.setRoleName(roleNames);

        processInfoEntity.setOldApprovalStatus(status);
        processInfoEntity.setNewApproverId(newApproverId);
        processInfoEntity.setRemark(remark);
        return sysProcessInfoDao.save(processInfoEntity);
    }

    /**
     *
     * @param deptNames
     * @param parentId
     * @return
     */
    private String getDeptNames(String deptNames, String parentId) {
        if (StringUtils.isNotEmpty(parentId)) {
            SysDeptEntity deptEntity = sysDeptDao.queryObject(parentId);
            deptNames = deptEntity.getName() + "-" + deptNames;
            if (StringUtils.isNotEmpty(deptEntity.getParentId())) {
                return getDeptNames(deptNames, deptEntity.getParentId());
            }
        }
        return deptNames;
    }

    /**
     *
     * @param sysProcessInfo
     * @return
     */
    @Override
    public int updateOutTime(SysProcessInfoEntity sysProcessInfo) {
        return sysProcessInfoDao.updateOutTime(sysProcessInfo);
    }

    /**
     *
     * @param processId
     * @param approvalType
     * @param status
     * @param newApproverId
     * @param remark
     * @return
     */
    @Override
    public int saveProcessInfoBySys(String processId, ProcessInfoEnum approvalType, Integer status, String newApproverId, String remark) {
        //当系统直接出了流程时
        String roleNames = "";
        SysProcessInfoEntity processInfoEntity = new SysProcessInfoEntity();
        processInfoEntity.setId(RandomUtil.randomString(32));
        processInfoEntity.setProcessId(processId);
        processInfoEntity.setId(RandomUtil.randomString(32));
        processInfoEntity.setApprovalType(approvalType.name());
        processInfoEntity.setCreateTime(new Date());
        processInfoEntity.setOldApproverId("sys");
        processInfoEntity.setDeptName("");
        processInfoEntity.setRoleName(roleNames);
        processInfoEntity.setOldApprovalStatus(status);
        processInfoEntity.setNewApproverId(newApproverId);
        processInfoEntity.setRemark(remark);
        return sysProcessInfoDao.save(processInfoEntity);
    }

    /**
     *
     * @param id
     * @return
     */
    @Override
    public int getOver(String id) {
        return sysProcessInfoDao.isOver(id);
    }

}
